//
//  NetWorkHandler.m
//  UI19_网络封装(delegate 回调)
//
//  Created by dllo on 16/1/7.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "NetWorkHandler.h"
#import "AFNetworking.h"
#import <CommonCrypto/CommonDigest.h>
@interface NetWorkHandler ()

@property (nonatomic,assign)BOOL net;
@end
@implementation NetWorkHandler
- (void)nexWorkHandlerJSONWithURL:(NSString *)urlString{
    
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                NSLog(@"未知网络");
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                
                self.net = NO;
                
                NSLog(@"没有网络(断网)");
                
                NSString *cook = @"cook/";
                NSString *behind = @".data";
                NSString *file = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                
                NSString* path =[file stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetWorkHandler md5HexDigest:urlString],behind]];
                
                NSMutableData *data = [NSMutableData dataWithContentsOfFile:path];
                
                NSError *errorJOSON = nil;
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorJOSON];
                
                if ([self.delegate respondsToSelector:@selector(haneldDidComplete:)]) {
                    
                    [self.delegate  haneldDidComplete:result];
                }
                
                
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                
                NSLog(@"2g/3g4g网");
                
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                NSLog(@"WIFI网络");
                
                // 将字符串进行转码 (URL 中不能含有中文等字符 )
                //NSString *temp = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
                
                // URL
                NSURL *url = [NSURL URLWithString:urlString];
                //NSURL *url = [NSURL URLWithString:temp];
                
                // session
                
                NSURLSession *session = [NSURLSession sharedSession];
                // add task
                
                NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                    
                    dispatch_sync(dispatch_get_main_queue(), ^(){
                        
                        NSString *cook = @"cook/";
                        NSString *behind = @".data";
                        NSString *file = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                       
                        NSLog(@"%@",NSHomeDirectory());
                        
                        NSString* path =[file stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetWorkHandler md5HexDigest:urlString],behind]];
                        [data writeToFile:path  atomically:YES];
                        
                        NSError *errorJOSON = nil;
                        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorJOSON];
                        
                        if ([self.delegate respondsToSelector:@selector(haneldDidComplete:)]) {
                            
                            [self.delegate  haneldDidComplete:result];
                        }
                        
                    });
                    
                }];
                
                [task resume];
                break;
        }
        
    }];
    
    [mgr startMonitoring];
    
}
///** 通过 NSURLSession 实现网络请求 */
//- (void)nexWorkHandlerJSONWithURL:(NSString *)urlString{
//
//    /** 将字符串进行转码 (URL 中不能含有中文等字符) 中文变成%*/
//    NSString *temp = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//    
//    
//    //url
//    NSURL *url = [NSURL URLWithString: temp];
//    
//    //session
//    NSURLSession *session = [NSURLSession sharedSession];
//    
//    //add task
//    NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//       
//        dispatch_async(dispatch_get_main_queue(), ^{
//        
//       
//        
//        NSError *errorJSON = nil;
//        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorJSON];
//        
//            
//            
//        if ([self.delegate respondsToSelector:@selector(haneldDidComplete:)]) {
//            
//            [self.delegate haneldDidComplete:result];
//            
//        }
//        
//    
//         });    
//        
//    }];
//
//
//    /** 开始任务 */
//    [task resume];
//
//}

+ (NSString *)md5HexDigest:(NSString*)input {
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (unsigned int)strlen(str), result);
    
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    NSString *mdfiveString = [hash lowercaseString];
    
    return mdfiveString;
}


+ (void)handlerJSONWithURL:(NSString *)urlstring delegate:(id<NetWorkHandlerDelegate>)delegate{



    NetWorkHandler *hander = [[NetWorkHandler alloc]init];
    [hander nexWorkHandlerJSONWithURL:urlstring];
    hander.delegate = delegate;


}




@end
